package com.modular.query;

import cn.hutool.core.collection.CollUtil;
import com.modular.json.JackJsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ffm
 * @version v1.0.0
 * @ClassName BatchQueryUtils
 * @description 功能描述
 * @date created in 2021/10/23 15:50
 */
public class BatchQuery<T, Q> {

    public final static Integer MAX_QUERY_LEN = 900;


    /**
     * 由于oracle最多只能in 1000条数据，所有对多余的需要分页查询
     *
     * @param call
     * @param list 查询中list
     * @return
     */
    public List<T> excute(IBatchQueryCall<T, Q> call, List<Q> list) {
        return excute(call, list, null, MAX_QUERY_LEN);
    }

    /**
     * 由于oracle最多只能in 1000条数据，所有对多余的需要分页查询
     *
     * @param call
     * @param list        查询中list
     * @param otherParams 其他参数
     * @return
     */
    public List<T> excute(IBatchQueryCall<T, Q> call, List<Q> list, Map<String, Object> otherParams) {
        return excute(call, list, otherParams, MAX_QUERY_LEN);
    }

    /**
     * 由于oracle最多只能in 1000条数据，所有对多余的需要分页查询
     *
     * @param call
     * @param list        查询中list
     * @param otherParams 其他参数
     * @param maxLen      一次最多使用的数量，默认900
     * @return
     */
    public List<T> excute(IBatchQueryCall<T, Q> call, List<Q> list, Map<String, Object> otherParams, Integer maxLen) {
        List<T> allList = new ArrayList<>();
        if (CollUtil.isEmpty(list)) {
            return allList;
        }
        List<T> tempList = null;
        if(list.size() < maxLen){
            tempList = call.query(list, otherParams);
            if(CollUtil.isNotEmpty(tempList)){
                allList.addAll(tempList);
            }
        }else{
            List<List<Q>> splitList = CollUtil.split(list,maxLen);
            for(List<Q> itemList:splitList){
                tempList = call.query(itemList, otherParams);
                if(CollUtil.isNotEmpty(tempList)){
                    allList.addAll(tempList);
                }
            }
        }
        return allList;
    }

    public static void main(String[] args) {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            temp.add("i" + i);
        }
        System.out.println(JackJsonUtil.toJson(temp));
        BatchQuery<String, String> batchQuery = new BatchQuery<>();
        List<String> resList = batchQuery.excute(new IBatchQueryCall() {
            @Override
            public List query(List list, Map otherParams) {
                System.out.println(JackJsonUtil.toJson(list));
                return list;
            }
        }, temp, null);
        System.out.println(JackJsonUtil.toJson(resList));
    }

}
